package com.ywx.yypicturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ywx.yypicturebackend.exception.BusinessException;
import com.ywx.yypicturebackend.exception.ErrorCode;
import com.ywx.yypicturebackend.exception.ThrowUtils;
import com.ywx.yypicturebackend.manager.CosManager;
import com.ywx.yypicturebackend.model.dto.space.SpaceAddRequest;
import com.ywx.yypicturebackend.model.dto.space.SpaceQueryRequest;
import com.ywx.yypicturebackend.model.entity.Picture;
import com.ywx.yypicturebackend.model.entity.Space;
import com.ywx.yypicturebackend.model.entity.User;
import com.ywx.yypicturebackend.model.enums.SpaceLevelEnum;
import com.ywx.yypicturebackend.model.vo.SpaceVO;
import com.ywx.yypicturebackend.model.vo.UserVO;
import com.ywx.yypicturebackend.service.PictureService;
import com.ywx.yypicturebackend.service.SpaceService;
import com.ywx.yypicturebackend.mapper.SpaceMapper;
import com.ywx.yypicturebackend.service.UserService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author ywx
 * @description 针对表【space(空间)】的数据库操作Service实现
 * @createDate 2025-05-21 10:41:14
 */
@Service
@NoArgsConstructor
@Slf4j
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
        implements SpaceService {

    @Resource
    UserService userService;

    @Resource
    @Lazy
    PictureService pictureService;

    @Resource
    CosManager cosManager;

    @Resource
    TransactionTemplate transactionTemplate;


    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        //数据转移
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest, space);
        //填充默认值
        if (StrUtil.isBlank(space.getSpaceName())) {
            space.setSpaceName("默认空间");
        }
        if (space.getSpaceLevel() == null) {
            //默认为普通版本
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getLevel());
        }
        //数据校验
        validSpace(space, true);

        //数据填充
        fillSpaceBySpaceLevel(space);
        Long userId = loginUser.getId();
        space.setUserId(userId);

        //权限校验
        if (SpaceLevelEnum.COMMON.getLevel() != spaceAddRequest.getSpaceLevel() && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }


        ConcurrentHashMap<Long, Object> lockMap = new ConcurrentHashMap<>();
        //线程安全,保证每个用户只有一个锁对象
        Object lock = lockMap.computeIfAbsent(userId, key -> new Object());

        synchronized (lock) {
            try {

                Long spaceId = transactionTemplate.execute(status -> {

                    //判断是否已经创建了空间
                    boolean exists = this.lambdaQuery().eq(Space::getUserId, loginUser.getId()).exists();
                    ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "一个用户最多创建一个私有空间");

                    boolean saveResult = this.save(space);
                    ThrowUtils.throwIf(!saveResult, ErrorCode.OPERATION_ERROR);

                    return space.getId();
                });

                return Optional.ofNullable(spaceId).orElse(-1L);

            } finally {
                //删除锁,防止大量锁对象占用空间
                lockMap.remove(lock);
            }

        }

    }

    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();

        if (spaceQueryRequest == null) {
            return queryWrapper;
        }


        Long id = spaceQueryRequest.getId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Long userId = spaceQueryRequest.getUserId();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();


        queryWrapper.eq(ObjectUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(spaceName), "spaceName", spaceName);
        queryWrapper.eq(ObjectUtil.isNotEmpty(spaceLevel), "spaceLevel", spaceLevel);


        //排序
        queryWrapper.orderBy(StrUtil.isNotBlank(sortField), "ascend".equals(sortOrder), sortField);


        return queryWrapper;
    }

    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        SpaceVO spaceVO = SpaceVO.objToVO(space);
        Long userId = spaceVO.getUserId();

        if (userId != null) {
            User user = userService.getById(userId);
            UserVO userVo = userService.getUserVo(user);
            spaceVO.setUser(userVo);
        }

        return spaceVO;
    }

    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        //拿到分页结果中的数据列表
        List<Space> spaceList = spacePage.getRecords();

        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        //如果分页数据为空,则直接返回即可
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }

        //对象列表 =》 封装对象列表
        List<SpaceVO> spaceVOList = spaceList.stream().map(SpaceVO::objToVO).collect(Collectors.toList());


        //关联查询用户信息
        Set<Long> userIdSet = spaceList.stream().map(Space::getId).collect(Collectors.toSet());
        //用户id映射用户对象
        Map<Long, List<User>> userIdUserListMap =
                userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));

        //填充信息
        spaceVOList.forEach(spaceVO -> {
            long userId = spaceVO.getUserId();
            User user = null;

            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUser(userService.getUserVo(user));

        });
        spaceVOPage.setRecords(spaceVOList);

        return spaceVOPage;
    }

    @Override
    public void validSpace(Space space, Boolean add) {
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);

        //从对象中取值
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        //获得等级枚举
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);

        //如果是创建
        if (add) {
            //校验空间名和空间级别
            if (StrUtil.isBlank(spaceName)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称不能为空");
            }
            if (spaceLevel == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间等级不能为空");
            }
        }

        //无论是新增还是修改,都要校验数据是否合法
        if (StrUtil.isNotBlank(spaceName) && spaceName.length() > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称不能大于50个字符");

        }
        if (spaceLevel != null && spaceLevelEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间等级不存在");
        }
    }


    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        Long maxCount = space.getMaxCount();
        Long maxSize = space.getMaxSize();
        //优先以管理员填充的为主
        if (maxSize == null) {
            space.setMaxSize(spaceLevelEnum.getMaxSize());
        }
        if (maxCount == null) {
            space.setMaxCount(spaceLevelEnum.getMaxCount());
        }

    }

    @Override
    public void deletePictureBySpaceId(Long spaceId) {
        //判断空间是否存在
        Space space = this.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");

        List<Picture> picturesBySpaceId = pictureService.getPicturesBySpaceId(spaceId);
        List<Long> pictureIds = picturesBySpaceId.stream().map(picture -> picture.getId()).collect(Collectors.toList());


        transactionTemplate.execute(status -> {
            //删除数据库中的图片
            boolean delete = pictureService.removeByIds(pictureIds);
            ThrowUtils.throwIf(!delete, ErrorCode.OPERATION_ERROR,"数据库图片删除失败");


            try {
                //删除cos中的图片

                //获取压缩图RUI
                List<String> pictureUrls = picturesBySpaceId.stream().map(picture -> {
                    try {
                        return new URI(picture.getUrl()).getPath().substring(1);
                    } catch (URISyntaxException e) {
                        throw new RuntimeException(e);
                    }
                }).collect(Collectors.toList());


                //获取缩略图RUI
                List<String> pictureThumbnailUrls = picturesBySpaceId.stream().map(picture -> {
                    try {
                        return new URI(picture.getThumbnailUrl()).getPath().substring(1);
                    } catch (URISyntaxException e) {
                        throw new RuntimeException(e);
                    }
                }).collect(Collectors.toList());


                //获取原图URI
                List<String> pictureOriginalUrls = picturesBySpaceId.stream().map(picture -> {
                    try {
                        return new URI(picture.getOriginalUrl()).getPath().substring(1);
                    } catch (URISyntaxException e) {
                        throw new RuntimeException(e);
                    }
                }).collect(Collectors.toList());

                //删除压缩图
                cosManager.deleteObjectByKeys((ArrayList<String>) pictureUrls);

                //删除缩略图
                if (CollUtil.isNotEmpty(pictureThumbnailUrls)) {
                    cosManager.deleteObjectByKeys((ArrayList<String>) pictureThumbnailUrls);
                }

                //删除原图,之前数据库有的数据没有原图url,所有需要判断一下
                if (CollUtil.isNotEmpty(pictureOriginalUrls)) {
                    cosManager.deleteObjectByKeys((ArrayList<String>) pictureOriginalUrls);
                }

            } catch (Exception e) {
                log.info("图片URL获取失败,可能未完全删除图片", e);
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"空间图片删除失败");
            }

            return true;
        });


    }

    @Override
    public void checkSpaceAuth(Space space, User loginUser) {
        if (!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

    }
}




